#include <my_header.h>

/* Usage:  */
// 两个线程对同一个共享变量分别加一百万次: 使用锁
#define TIMES 10000000
// 提取结构体
typedef struct share_value{
    int sum;    // 初始化累加的sum
    pthread_mutex_t mLock;  // 定义锁
} share_value_t;
// 子线程
void * func(void *arg){
    // 结构体传入锁
    share_value_t *pshareValue = (share_value_t *)arg;
    printf("child thread is runing \n");
    // 累加
    for(int i = 0; i<TIMES; i++){
        pthread_mutex_lock(&pshareValue->mLock);
        pshareValue->sum ++;
        pthread_mutex_unlock(&pshareValue->mLock);
    }
    printf("child thread stop \n");
    return NULL;
}

int main(void)
{
    // 初始化结构体
    share_value_t shareValue;
    shareValue.sum = 0;
    pthread_mutex_init(&shareValue.mLock, NULL);

    pthread_t pid;
    pthread_create(&pid,NULL,func, &shareValue);

    printf("main thread is runing \n");
    for(int i = 0; i<TIMES; i++){
        pthread_mutex_lock(&shareValue.mLock);
        shareValue.sum++;
        pthread_mutex_unlock(&shareValue.mLock);
    }
    printf("main thread stop \n");
    // 捕获子线程id
    pthread_join(pid, NULL);
    printf("all over, global = %d \n", shareValue.sum);
    //销毁锁
    pthread_mutex_destroy(&shareValue.mLock);
    return 0;
}

